#include "AQ_HashTable.h"



static unsigned long StrHash(const char * szKey) {
	unsigned long h = 0;		
	
	for( ; *str; ++str)	{
		h = (h << 5) - h + *str;   			
		// equal:  h = 31 * h + (*p);			
		//    stl :  h = 5*h + *s;		
	}		
	return h;
}


AQ_HashElement* AQ_HashTable::Get(void* k) const {
	unsigned long 	iHashKey = 0;
	AQ_HashElement* pHE = NULL;

	for(int i=0; i<m_ulHashBucketNums && m_HT[i]!=0; i++) {
		iHashKey = _KeyHashFunc(k) % m_HT[i];
		pHE = &(m_HT[i][iHashKey]);

		if(_KeyEqualFunc(k, pHE->pKey)) {
			return pHE;
		}
	}

	return NULL;
}

int AQ_HashTable::Update(AQ_HashElement* pNewHE) {
	AQ_HashElement* pOldHE = Get(pNewHE->pKey);
	if(NULL == pOldHE) {
		m_iCount++;
		return Add(pNewHE);
	}
	else {
		memcpy(pOldHE, pNewHE, sizeof(AQ_HashElement));
	}

	return 0;
}

int AQ_HashTable::Del(void* k) {
	AQ_HashElement* pHE = Get(k);

	if(!NULL == pHE) {
		memset(pHE, 0, sizeof(pHE));
		m_iCount--;
	}
	else {
		return -1;
	}

	return 0;
}

int AQ_HashTable::Count() const {
	return m_iCount;
}

bool AQ_HashTable::IsEmpty() const {
	return (0 == m_iCount);
}

int AQ_HashTable::UsageRate() const {
	return m_iCount * 100 / (m_iHashBucketLen * m_iHashBucketNums);
}

int AQ_HashTable::Clear() {

	return 0;
}

void AQ_HashTable::SetHashBucketNums(int iNums) {
	m_iHashBucketNums = iNums;
}


bool AQ_HashTable::IsPrimeNum(int N) {
	if(N < 2)			return false;
	if(N==2 || N==3)	return true;
	if(N % 2 == 0)		return false;

	double root = sqrt((double)N);
	if(double(long(root) == root))	return false;

	long beg = 3;
	long end = long(root) + 1;
	if(end < beg)		return false;

	for(long i=beg; i!=end; i++) {
		if(N % i == 0)	return 	false;
	}
	
	return true;
}